package com.jsz.peini.service.user;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.UUID;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.node.JsonNodeFactory;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.github.pagehelper.PageHelper;
import com.jsz.peini.bean.coupon.CouponInfo;
import com.jsz.peini.bean.user.AccountCode;
import com.jsz.peini.bean.user.UserAccount;
import com.jsz.peini.bean.user.UserInfo;
import com.jsz.peini.bean.user.UserInfoExample;
import com.jsz.peini.bean.user.UserInfoExample.Criteria;
import com.jsz.peini.bean.user.UserJudge;
import com.jsz.peini.bean.user.UserLogin;
import com.jsz.peini.common.constants.Constants;
import com.jsz.peini.common.util.AppPush;
import com.jsz.peini.common.util.AppSecretUtil;
import com.jsz.peini.common.util.CommonUtils;
import com.jsz.peini.common.util.FileUtils;
import com.jsz.peini.common.util.MDUtil;
import com.jsz.peini.common.util.PeiniUtils;
import com.jsz.peini.common.util.SmsSendUtil;
import com.jsz.peini.emchat.api.EasemobIMUsers;
import com.jsz.peini.mapper.app.AppActivityUserMapper;
import com.jsz.peini.mapper.comm.ImageFilterResultMapper;
import com.jsz.peini.mapper.coupon.CouponHistoryMapper;
import com.jsz.peini.mapper.coupon.CouponInfoMapper;
import com.jsz.peini.mapper.coupon.CouponUserMapper;
import com.jsz.peini.mapper.user.AccountCodeMapper;
import com.jsz.peini.mapper.user.UserAccountMapper;
import com.jsz.peini.mapper.user.UserInfoMapper;
import com.jsz.peini.mapper.user.UserLoginMapper;
import com.jsz.peini.mapper.user.UserSmsMapper;
import com.jsz.peini.redis.base.RedisConstants;
import com.jsz.peini.redis.base.RedisUtil;
import com.jsz.peini.redis.base.SerializeUtil;
import com.jsz.peini.redis.util.UserRedisUtil;
import com.jsz.peini.service.coupon.CouponInfoService;
import com.jsz.peini.vo.ImgVo;
import com.jsz.peini.vo.UserSearchVo;
import com.jsz.peini.vo.UserVo;

@Service
public class UserInfoService {
	private static final Logger logger = LoggerFactory.getLogger(UserInfoService.class);
	@Resource
	private UserInfoMapper userInfoMapper;
	@Resource
	private AccountCodeMapper accountCodeMapper;
	@Resource
	private UserLoginMapper userLoginMapper;
	@Resource
	private UserAccountMapper userAccountMapper;
	@Resource
	private ImageFilterResultMapper imageFilterResultMapper;
	@Resource
	private CouponInfoMapper couponInfoMapper;
	@Resource
	private CouponUserMapper couponUserMapper;
	@Resource
	private CouponHistoryMapper couponHistoryMapper;
	@Resource
	private UserSmsMapper userSmsMapper;
	@Resource
	private CouponInfoService couponInfoService;
	@Resource
	private UserInfoService userInfoService;
	@Resource
	private AppActivityUserMapper appActivityUserMapper;
	
	/**
	 * 用户注册登录
	 * @author Han Guohong
	 * @param request
	 * @param sex
	 * @param birthday
	 * @param nowProvince
	 * @param nowCity
	 * @param age
	 * @param userName
	 * @param userPassword
	 * @param appA
	 * @param devNo
	 * @param channel
	 * @param devtype
	 * @return
	 */
	@Transactional
	public HashMap<String, Object> register(HttpServletRequest request,
			Integer sex,
			String birthday,
			Integer nowProvince,
			Integer nowCity,
			Integer age,
			String userName,
			String userPassword,
			String appA,  //交换参数
			String devNo,
			String channel,
			Integer devtype){
		
		HashMap<String, Object> infoMap = new HashMap<String, Object>();
		try {
			UserLogin userLogin = new UserLogin();
			
			UserInfo userInfo = new UserInfo();
			userInfo.setAge(age);
			userInfo.setSex(sex);
			userInfo.setBirthday(birthday);
			userInfo.setNowProvince(nowProvince);
			userInfo.setNowCity(nowCity);
			userInfo.setIsPhone(1);
			userInfo.setActiveTime(new Date());
			
			List<UserLogin> list = userLoginMapper.selectByUserName(userName);
			if(list.size() > 0){
				infoMap.put("resultCode", Constants.FAIL);
				infoMap.put("resultDesc", "该用户已存在");
				
				return infoMap;
			}
			/*userLogin = 
			if (userLogin != null) {
				infoMap.put("resultCode", Constants.FAIL);
				infoMap.put("resultDesc", "该用户已存在");
				
				return infoMap;
			}*/
			
			userLogin = new UserLogin();
			//userLogin.setUserPassword(MDUtil.encodePwd(userPassword));
			userLogin.setUserPassword(userPassword);
			userLogin.setUserName(userName);
			// 插入用户登录表
			int insertNum = userLoginMapper.insertByUserLogin(userLogin);
			
			if (insertNum != 0) {
				
				//userLogin = userLoginService.selectByUserName(userName);
				userInfo.setUserLoginId(userLogin.getId());
				userInfo.setId(UUID.randomUUID().toString().replace("-", ""));
				userInfo.setNickname(CommonUtils.getRandom());
				userInfo.setUserPhone(userName);
				userInfo.setRegTime(new Date());
				userInfo.setActiveTime(new Date());
				userInfo.setUpdateTime(new Date());
				userInfo.setIsRank(1);
				if(StringUtils.isNotBlank(devNo)){
					userInfo.setDevNo(devNo);
				}
				if(StringUtils.isNotBlank(channel)){
					userInfo.setChannel(channel);
				}
				if(devtype != null){
					userInfo.setDevtype(devtype);
				}
				//int insertUserInfoNum = userInfoService.insertByUserLoginId(userInfo);
				int insertUserInfoNum = userInfoMapper.insertSelective(userInfo);
				if (insertUserInfoNum != 0) {
					
					infoMap.put("resultCode", Constants.SUCCESS);
					infoMap.put("resultDesc", "注册成功");
					//userInfo = userInfoService.selectByUserLoginId(userLogin.getId());
					userInfo = selectByPrimaryKey(userInfo.getId());
					
					int selfNum = getselfNum(userInfo);//获取资料得分
					userInfo.setSelfNum(selfNum);
					
					userInfo.setReputation(PeiniUtils.getCredit(userInfo,1));
					userInfoMapper.updateByPrimaryKey(userInfo);
					
					// 建立用户账户表
					//userAccountService.insert(userInfo.getId());
					UserAccount userAccount = new UserAccount();
					userAccount.setUserId(userInfo.getId());
					userAccountMapper.insertSelective(userAccount);
					LinkedHashMap<String, Object> userMap = new LinkedHashMap<String, Object>();
					
					String userToken = UUID.randomUUID().toString().replace("-", "");
					
					//userMap.put("id", userInfo.getId());
					userMap.put("id", userToken);
					userMap.put("userLoginId", userInfo.getUserLoginId());
					userMap.put("nickname","");
					userMap.put("imageHead",
							StringUtils.isNotBlank(userInfo.getImageHead()) ? userInfo.getImageHead() : "");
					userMap.put("sex", userInfo.getSex());
					userMap.put("userPhone", userName);
					
					// 登录成功生成新的token
					//EhcacheUtil.getInstance().put("userCache", userInfo.getId().toString(), userToken);
					UserRedisUtil.updateUserToken(userInfo.getId(), userToken);

					// edit by han 2017-1-6
					// userInfoService.updateCredit(userInfo.getId());
					//PeiniUtils.regUserInfos.add(userInfo);
					RedisUtil.lpush(RedisConstants.USER_REG.getBytes(), SerializeUtil.serialize(userInfo));
					//EhcacheUtil.getInstance().put("accCodeCache", "codeList", PeiniUtils.regUserInfos);
					
					getNewAward(userInfo);
					
					//将新用户信息写入缓存
					UserVo userVo = new UserVo();
					userVo.setAcountId(String.valueOf(userAccount.getId()));
					userVo.setUserId(userInfo.getId());
					userVo.setUserLoginId(userLogin.getId().toString());
					userVo.setBuyList(new BigDecimal("0"));
					userVo.setGoldList(new BigDecimal("0"));
					userVo.setIntegrityList(new BigDecimal("0"));
					UserRedisUtil.addUserToRedis(userVo);
					
					ObjectNode datanode = JsonNodeFactory.instance.objectNode();
			        datanode.put("username",userLogin.getUserName());
			        datanode.put("password", "123456");
			        datanode.put("nickname", PeiniUtils.updateNickName(userInfo.getNickname(), userInfo.getAccCode()));
			        EasemobIMUsers.createNewIMUserSingle(datanode);
			        
					infoMap.put("userToken", userToken);
					infoMap.put("userInfo", userMap);
					
					String serverB = AppSecretUtil.getAppSecret(userInfo.getId().toString(), appA);
					infoMap.put("serverB", serverB);
				} else {
					infoMap.put("resultCode", Constants.FAIL);
					infoMap.put("resultDesc", "网络请求失败");
				}
			}
		} catch (Exception e) {
			infoMap.put("resultCode", Constants.EXCEPTION);
			infoMap.put("resultDesc", Constants.EXCEPTION_DESC);
			logger.error(e.getMessage(),e);
			throw e;
		}
		return infoMap;
	}
	/**
	 * 04-21新版注册 service层
	 * @param request
	 * @param userName
	 * @param userPassword
	 * @param appA
	 * @param devNo
	 * @param channel
	 * @param devtype
	 * @return
	 */
	@Transactional
	public HashMap<String, Object> registerNew(HttpServletRequest request,
												String userName,
												String userPassword,
												Integer thirdType,////三方类型：1QQ,2微信；3新浪微博
												String thirdName,
												String appA,  //交换参数
												String devNo,
												String channel,
												Integer devtype,
												String recId){
		HashMap<String, Object> infoMap = new HashMap<String, Object>();
		try {
			UserLogin userLogin = new UserLogin();
			
			UserInfo userInfo = new UserInfo();
			userInfo.setIsPhone(1);
			userInfo.setActiveTime(new Date());
			
			List<UserLogin> list = userLoginMapper.selectByUserName(userName);
			if(list.size() > 0){
				infoMap.put("resultCode", Constants.FAIL);
				infoMap.put("resultDesc", "该用户已存在");
				return infoMap;
			}
			
			if(StringUtils.isNotBlank(recId)){
				List<UserInfo> userList = userInfoMapper.getUserInfoByAccCode(recId);
				if(userList.size()>0){
					UserInfo recUser = userList.get(0);
					userInfo.setRecommendUserId(recUser.getId());
				}else{
					infoMap.put("resultCode", Constants.FAIL);
					infoMap.put("resultDesc", "您输入的推荐人不存在");
					return infoMap;
				}
			}
			
			userLogin = new UserLogin();
			//userLogin.setUserPassword(MDUtil.encodePwd(userPassword));
			userLogin.setUserPassword(userPassword);
			userLogin.setUserName(userName);
			userLogin.setThirdtype(thirdType);
			userLogin.setThirdName(thirdName);
			
			// 插入用户登录表
			int insertNum = userLoginMapper.insertByUserLogin(userLogin);
			if (insertNum != 0) {
				userInfo.setUserLoginId(userLogin.getId());
				userInfo.setId(UUID.randomUUID().toString().replace("-", ""));
				userInfo.setNickname(CommonUtils.getRandom());
				userInfo.setUserPhone(userName);
				userInfo.setRegTime(new Date());
				userInfo.setActiveTime(new Date());
				userInfo.setUpdateTime(new Date());
				userInfo.setImgheadIsdelete(0);
				userInfo.setIsRank(1);
				if(StringUtils.isNotBlank(devNo)){
					userInfo.setDevNo(devNo);
				}
				if(StringUtils.isNotBlank(channel)){
					userInfo.setChannel(channel);
				}
				if(devtype != null){
					userInfo.setDevtype(devtype);
				}
				
				//插入到用户信息表
				int insertUserInfoNum = userInfoMapper.insertSelective(userInfo);
				
				RedisUtil.lpush(RedisConstants.USER_REG.getBytes(), SerializeUtil.serialize(userInfo));
				
				if (insertUserInfoNum != 0) {
					infoMap.put("resultCode", Constants.SUCCESS);
					infoMap.put("resultDesc", "注册成功");
					
					userInfo = selectByPrimaryKey(userInfo.getId());
					int selfNum = getselfNum(userInfo);//获取资料得分
					userInfo.setSelfNum(selfNum);
					userInfo.setReputation(PeiniUtils.getCredit(userInfo,1));
					userInfoMapper.updateByPrimaryKeySelective(userInfo);
					
					// 建立用户账户表
					//userAccountService.insert(userInfo.getId());
					UserAccount userAccount = new UserAccount();
					userAccount.setUserId(userInfo.getId());
					userAccountMapper.insertSelective(userAccount);
					LinkedHashMap<String, Object> userMap = new LinkedHashMap<String, Object>();
					
					String userToken = UUID.randomUUID().toString().replace("-", "");
					
					userMap.put("id", userToken);
					userMap.put("userLoginId", userInfo.getUserLoginId());
					userMap.put("nickname","");
					userMap.put("imageHead",
							StringUtils.isNotBlank(userInfo.getImageHead()) ? userInfo.getImageHead() : "");
					userMap.put("userPhone", userName);
					// 登录成功生成新的token
					UserRedisUtil.updateUserToken(userInfo.getId(), userToken);
					
					getNewAward(userInfo);
					
					//将新用户信息写入缓存
					UserVo userVo = new UserVo();
					userVo.setAcountId(String.valueOf(userAccount.getId()));
					userVo.setUserId(userInfo.getId());
					userVo.setUserLoginId(userLogin.getId().toString());
					userVo.setBuyList(new BigDecimal("0"));
					userVo.setGoldList(new BigDecimal("0"));
					userVo.setIntegrityList(new BigDecimal("0"));
					UserRedisUtil.addUserToRedis(userVo);
					
					ObjectNode datanode = JsonNodeFactory.instance.objectNode();
			        datanode.put("username",userLogin.getUserName());
			        datanode.put("password", "123456");
			        datanode.put("nickname", PeiniUtils.updateNickName(userInfo.getNickname(), userInfo.getAccCode()));
			        EasemobIMUsers.createNewIMUserSingle(datanode);
					
			        infoMap.put("userToken", userToken);
					infoMap.put("userInfo", userMap);
					
					String serverB = AppSecretUtil.getAppSecret(userInfo.getId().toString(), appA);
					infoMap.put("serverB", serverB);
					
					//消息推送
					JSONObject object = new JSONObject();
					object.put("title", "系统消息");
					object.put("content", "漫长的等待终于盼来了您，接下来的日子由陪你守护！陪你使用秘诀第一步：赶紧完善资料并上传真实头像，让我们玩转任务，认识更多的新朋友吧~");
					object.put("paramId", userInfo.getId());
					object.put("type", 201);
					UserInfo newuserInfo = userInfoMapper.selectByPrimaryKey(userInfo.getId());
					AppPush.sendPush(object,newuserInfo.getUserPhone().split(","));
					
					SmsSendUtil.sendSmsFit(null, userInfo.getId(), userInfo.getId(), 201, "漫长的等待终于盼来了您，接下来的日子由陪你守护！陪你使用秘诀第一步：赶紧完善资料并上传真实头像，让我们玩转任务，认识更多的新朋友吧~");
					
					if(StringUtils.isBlank(userInfo.getAccCode())){
						RedisUtil.lpush(RedisConstants.USER_REG.getBytes(), SerializeUtil.serialize(userInfo));
					}
				}else {
					infoMap.put("resultCode", Constants.FAIL);
					infoMap.put("resultDesc", "网络请求失败");
				}
				
			}
			
		} catch (Exception e) {
			infoMap.put("resultCode", Constants.EXCEPTION);
			infoMap.put("resultDesc", Constants.EXCEPTION_DESC);
			logger.error(e.getMessage(),e);
			throw e;
		}
		return infoMap;
	}
	/**
	 * 领取新用户奖励
	 * @author Han Guohong
	 * @param userInfo
	 */
	private void getNewAward(UserInfo userInfo){
		//获取新用户注册奖励
		List<CouponInfo> couponList = couponInfoMapper.getCouponInfoNewAward();
		couponInfoService.rushBuyCouponResult(couponList, userInfo.getId(),10,null);
		/*for (CouponInfo couponInfo : couponList) {
			String regCnt = RedisUtil.get(RedisConstants.COUPON_GET+couponInfo.getId());*/
			
			
			/*
			if(StringUtils.isBlank(regCnt)){
				CouponUserExample cuExample = new CouponUserExample();
				cuExample.createCriteria().andCouponIdEqualTo(couponInfo.getId());
				int cnt = couponUserMapper.countByExample(cuExample);
				RedisUtil.set(RedisConstants.COUPON_GET+couponInfo.getId(), String.valueOf(cnt));
				regCnt = String.valueOf(cnt);
			}
			
			int recvCnt = Integer.parseInt(regCnt);
			if(recvCnt < couponInfo.getCouponNum()){
				Jedis redis = RedisUtil.getRedis();
				redis.watch(RedisConstants.COUPON_GET+couponInfo.getId());
				Transaction trsn = redis.multi();
				trsn.set(RedisConstants.COUPON_GET+couponInfo.getId(), String.valueOf(recvCnt));
				List<Object> objList = trsn.exec();
				if(objList != null && objList.size() > 0){
					//领取成功，将数据写入缓存
					RedisUtil.set(RedisConstants.COUPON_GET+couponInfo.getId(),String.valueOf(recvCnt+1));
					
					CouponUser couponUser = new CouponUser();
					couponUser.setGetTime(new Date());
					couponUser.setId(UUID.randomUUID().toString().replace("-", ""));
					couponUser.setCouponId(couponInfo.getId());
					couponUser.setCouponNum(1);
					couponUser.setGetType(10);
					couponUser.setUserId(userInfo.getId());
					couponUserMapper.insert(couponUser);
					
					CouponHistory chis = new CouponHistory();
					chis.setHisId(UUID.randomUUID().toString().replace("-", ""));
					chis.setCreateTime(new Date());
					chis.setUserId(couponUser.getUserId());
					chis.setOpType(1);
					chis.setIsFinish(1);
					chis.setValNum(1l);
					chis.setHisType(10);
					chis.setParamId(couponUser.getParamId());
					chis.setIsDel(1);
					chis.setCouponId(couponUser.getCouponId());
					couponHistoryMapper.insertSelective(chis);
					
					couponInfo = couponInfoMapper.selectByPrimaryKey(couponInfo.getId());
					Long recvNum = (long)recvCnt+1;
					couponInfo.setReceivenum(recvNum);
					couponInfoMapper.updateByPrimaryKey(couponInfo);
					
					UserSms userSms = new UserSms();
					userSms.setSmsid(UUID.randomUUID().toString().replace("-", ""));
					userSms.setIsremind(1);
					userSms.setParamid(couponInfo.getId().toString());
					userSms.setReceivdel(0);
					userSms.setSenddel(0);
					userSms.setSendtime(new Date());
					userSms.setSmscontent("您有新的优惠券啦!");
					userSms.setSmstype(10);
					userSms.setToid(userInfo.getId());
					userSmsMapper.insertSelective(userSms);
				}
			}*/
		//}
	}
	
	/**
	 * 用户补充资料
	 * @author Han Guohong
	 * @param request
	 * @param sex
	 * @param birthday
	 * @param nowProvince
	 * @param nowCity
	 * @param age
	 * @param appA
	 * @return
	 */
	@Transactional
	public HashMap<String, Object> addUserInfo(HttpServletRequest request,
			String userId,
			Integer sex,
			String birthday,
			Integer nowProvince,
			Integer nowCity,
			Integer age,
			String appA,
			String devNo,
			Integer devtype
			){
		
		HashMap<String, Object> infoMap = new HashMap<String, Object>();
		try {
			UserInfo userInfo = userInfoMapper.selectByPrimaryKey(userId);
			userInfo.setAge(age);
			userInfo.setSex(sex);
			userInfo.setBirthday(birthday);
			userInfo.setNowProvince(nowProvince);
			userInfo.setNowCity(nowCity);
			userInfo.setDevNo(devNo);
			userInfo.setDevtype(devtype);
			
			userInfoMapper.updateByPrimaryKey(userInfo);
			
			int selfNum = getselfNum(userInfo);//获取资料得分
			userInfo.setSelfNum(selfNum);
			
			userInfo.setReputation(PeiniUtils.getCredit(userInfo,1));
			userInfoMapper.updateByPrimaryKey(userInfo);
			
			LinkedHashMap<String, Object> userMap = new LinkedHashMap<String, Object>();
			
			String userToken = UUID.randomUUID().toString().replace("-", "");
			
			userMap.put("id", userToken);
			userMap.put("userLoginId", userInfo.getUserLoginId());
			userMap.put("nickname",
					StringUtils.isNotBlank(userInfo.getNickname()) ? PeiniUtils.updateNickName(userInfo.getNickname(),userInfo.getAccCode()) : "");
			userMap.put("imageHead",
					StringUtils.isNotBlank(userInfo.getImageHead()) ? userInfo.getImageHead() : "");
			userMap.put("sex", userInfo.getSex());
			userMap.put("userPhone", userInfo.getUserPhone());
			
			// 登录成功生成新的token
			UserRedisUtil.updateUserToken(userInfo.getId(), userToken);
			
			RedisUtil.lpush(RedisConstants.USER_REG.getBytes(), SerializeUtil.serialize(userInfo));
			
			getNewAward(userInfo);
			
			ObjectNode datanode = JsonNodeFactory.instance.objectNode();
	        datanode.put("username",userInfo.getUserPhone());
	        datanode.put("password", "123456");
	        datanode.put("nickname", userInfo.getNickname());
	        EasemobIMUsers.createNewIMUserSingle(datanode);
	        
			infoMap.put("userToken", userToken);
			infoMap.put("userInfo", userMap);
			
			
			String serverB = AppSecretUtil.getAppSecret(userInfo.getId().toString(), appA);
			infoMap.put("serverB", serverB);
			
			//消息推送
			JSONObject object = new JSONObject();
			object.put("title", "系统消息");
			object.put("content", "恭喜您资料完善成功！陪你小秘书正马不停蹄地为您审核头像，审核期间除任务互动外，其他功能均可正常使用哦~");
			object.put("type", 202);
			object.put("paramId", userInfo.getId());
			object.put("paramId", userInfo.getId());
			AppPush.sendPush(object,userInfo.getUserPhone().split(","));
			
			SmsSendUtil.sendSmsFit(null, userInfo.getId(), userInfo.getId(), 202, "恭喜您资料完善成功！陪你小秘书正马不停蹄地为您审核头像，审核期间除任务互动外，其他功能均可正常使用哦~");
			infoMap.put("resultCode", Constants.SUCCESS);
			infoMap.put("resultDesc", "成功");
		} catch (Exception e) {
			infoMap.put("resultCode", Constants.EXCEPTION);
			infoMap.put("resultDesc", Constants.EXCEPTION_DESC);
			logger.error(e.getMessage(),e);
			throw e;
		}
		return infoMap;
	}
	
	@Transactional
	public HashMap<String, Object> addUserInfoNew(HttpServletRequest request,
			String userId,
			Integer sex,
			String birthday,
			String nickName,
			Integer age,
			String appA,
			String devNo,
			Integer devtype,
			MultipartFile file
			){
		
		HashMap<String, Object> infoMap = new HashMap<String, Object>();
		try {
			UserInfo userInfo = userInfoMapper.selectByPrimaryKey(userId);
			userInfo.setAge(age);
			userInfo.setSex(sex);
			userInfo.setBirthday(birthday);
			userInfo.setNickname(nickName);
			userInfo.setDevNo(devNo);
			userInfo.setDevtype(devtype);
			
			if (!file.isEmpty()) {
	        	HashMap<String, Object> userMap = userInfoService.getUserInfoAndLoginAccountInfo(userId);
	        	
				String filePath = "/upload/headImg/"+userMap.get("mobileNo").toString()+".png";
				
		        String resultPath = "";
		        
		        resultPath = FileUtils.uploadFile(file, filePath);
				userInfo.setImageHead(resultPath);
				userInfo.setImgheadUpdateTime(new Date());
				userInfo.setImgheadIsdelete(0);
				
				ImgVo imgVo = new ImgVo();
				imgVo.setImgUrl(resultPath);
				imgVo.setParamId(userId);
				imgVo.setType(2);
				RedisUtil.lpush(RedisConstants.IMG_CHECK.getBytes(), SerializeUtil.serialize(imgVo));
			}
			
			userInfoMapper.updateByPrimaryKey(userInfo);
			
			int selfNum = getselfNum(userInfo);//获取资料得分
			userInfo.setSelfNum(selfNum);
			
			userInfo.setReputation(PeiniUtils.getCredit(userInfo,1));
			userInfoMapper.updateByPrimaryKey(userInfo);
			
			LinkedHashMap<String, Object> userMap = new LinkedHashMap<String, Object>();
			
			String userToken = UUID.randomUUID().toString().replace("-", "");
			
			userMap.put("id", userToken);
			userMap.put("userLoginId", userInfo.getUserLoginId());
			userMap.put("nickname",
					StringUtils.isNotBlank(userInfo.getNickname()) ? PeiniUtils.updateNickName(userInfo.getNickname(),userInfo.getAccCode()) : "");
			userMap.put("imageHead",
					StringUtils.isNotBlank(userInfo.getImageHead()) ? userInfo.getImageHead() : "");
			userMap.put("sex", userInfo.getSex());
			userMap.put("userPhone", userInfo.getUserPhone());
			
			// 登录成功生成新的token
			UserRedisUtil.updateUserToken(userInfo.getId(), userToken);
			
			//RedisUtil.lpush(RedisConstants.USER_REG.getBytes(), SerializeUtil.serialize(userInfo));
			
			getNewAward(userInfo);
			
			ObjectNode datanode = JsonNodeFactory.instance.objectNode();
	        datanode.put("username",userInfo.getUserPhone());
	        datanode.put("password", "123456");
	        datanode.put("nickname", userInfo.getNickname());
	        EasemobIMUsers.createNewIMUserSingle(datanode);
	        
			infoMap.put("userToken", userToken);
			infoMap.put("userInfo", userMap);
			
			
			String serverB = AppSecretUtil.getAppSecret(userInfo.getId().toString(), appA);
			infoMap.put("serverB", serverB);
			
			//消息推送
			JSONObject object = new JSONObject();
			object.put("title", "系统消息");
			object.put("content", "恭喜您资料完善成功！陪你小秘书正马不停蹄地为您审核头像，审核期间除任务互动外，其他功能均可正常使用哦~");
			object.put("type", 202);
			object.put("paramId", userInfo.getId());
			object.put("paramId", userInfo.getId());
			AppPush.sendPush(object,userInfo.getUserPhone().split(","));
			
			SmsSendUtil.sendSmsFit(null, userInfo.getId(), userInfo.getId(), 202, "恭喜您资料完善成功！陪你小秘书正马不停蹄地为您审核头像，审核期间除任务互动外，其他功能均可正常使用哦~");
			infoMap.put("addUserInfo", "1");
			infoMap.put("resultCode", Constants.SUCCESS);
			infoMap.put("resultDesc", "成功");
		} catch (Exception e) {
			infoMap.put("resultCode", Constants.EXCEPTION);
			infoMap.put("resultDesc", Constants.EXCEPTION_DESC);
			logger.error(e.getMessage(),e);
			throw e;
		}
		return infoMap;
	}
	
	/**
	 * 新三方注册
	 * @author Han Guohong
	 * @param request
	 * @param userName
	 * @param thirdType
	 * @param thirdName
	 * @param nickname
	 * @param appA
	 * @param devNo
	 * @param channel
	 * @param devtype
	 * @return
	 */
	public HashMap<String, Object> registerThirdUserLoginNew(
			HttpServletRequest request, 
			String userName, 
			Integer thirdType,
			String thirdName,
			String appA, 
			String devNo, 
			String channel,
			Integer devtype) {
		HashMap<String, Object> infoMap = new HashMap<String, Object>();
		try {
			UserLogin userLogin = new UserLogin();
			
			UserInfo userInfo = new UserInfo();
			userInfo.setUserPhone(userName);
			userInfo.setIsPhone(1);
			userInfo.setActiveTime(new Date());
			
			userLogin.setUserName(userName);
			userLogin.setThirdtype(thirdType);
			userLogin.setThirdName(thirdName);
			
			List<UserLogin> list = userLoginMapper.selectByUserName(userName);
			if(list.size() > 0){
				infoMap.put("isExist", Constants.FAIL);
				infoMap.put("resultCode", Constants.SUCCESS);
				infoMap.put("resultDesc", "该用户已存在");
				return infoMap;
			}
			
			int insertNum = userLoginMapper.registerThirdUserLogin(userLogin);
			if (insertNum != 0) {
				
				userInfo.setId(UUID.randomUUID().toString().replace("-", ""));
				
				userInfo.setImageHead("");
				
				userInfo.setUserLoginId(userLogin.getId());
				/*if(StringUtils.isNotBlank(nickname)){
					userInfo.setNickname(nickname);
				}else{
					userInfo.setNickname(CommonUtils.getRandom());
				}*/
				
				userInfo.setRegTime(new Date());
				userInfo.setActiveTime(new Date());
				userInfo.setUpdateTime(new Date());
				userInfo.setImgheadIsdelete(0);
				userInfo.setIsRank(1);
				
				if(StringUtils.isNotBlank(devNo)){
					userInfo.setDevNo(devNo);
				}
				if(StringUtils.isNotBlank(channel)){
					userInfo.setChannel(channel);
				}
				if(devtype != null){
					userInfo.setDevtype(devtype);
				}
				
				int insertUserInfoNum = userInfoMapper.insertSelective(userInfo);
				
				if (insertUserInfoNum != 0) {
					infoMap.put("isExist", Constants.SUCCESS);
					infoMap.put("resultCode", Constants.SUCCESS);
					infoMap.put("resultDesc", "注册成功");
					userInfo = userInfoMapper.selectByPrimaryKey(userInfo.getId());
					
					int selfNum = getselfNum(userInfo);//获取资料得分
					userInfo.setSelfNum(selfNum);
					
					userInfo.setReputation(PeiniUtils.getCredit(userInfo,1));
					
					userInfoMapper.updateByPrimaryKey(userInfo);
					
					// 建立用户账户表
					UserAccount userAccount = new UserAccount();
					userAccount.setUserId(userInfo.getId());
					userAccountMapper.insertSelective(userAccount);
					
					LinkedHashMap<String, Object> userMap = new LinkedHashMap<String, Object>();
					
					// 登录成功生成新的token
					String userToken = UUID.randomUUID().toString().replace("-", "");
					
					userMap.put("id", userToken);
					userMap.put("userLoginId", userInfo.getUserLoginId());
					userMap.put("nickname",
							StringUtils.isNotBlank(userInfo.getNickname()) ?PeiniUtils.updateNickName( userInfo.getNickname(), userInfo.getAccCode()): "");
					userMap.put("imageHead",
							StringUtils.isNotBlank(userInfo.getImageHead()) ? userInfo.getImageHead() : "");
					userMap.put("sex", userInfo.getSex());
					userMap.put("userPhone", userName);
					
					UserRedisUtil.updateUserToken(userInfo.getId(), userToken);
					
					getNewAward(userInfo);
					
					RedisUtil.lpush(RedisConstants.USER_REG.getBytes(), SerializeUtil.serialize(userInfo));
					
					//将新用户信息写入缓存
					UserVo userVo = new UserVo();
					userVo.setAcountId(String.valueOf(userAccount.getId()));
					userVo.setUserId(userInfo.getId());
					UserRedisUtil.addUserToRedis(userVo);
					
					ObjectNode datanode = JsonNodeFactory.instance.objectNode();
			        datanode.put("username",userLogin.getUserName());
			        datanode.put("password", "123456");
			        datanode.put("nickname", PeiniUtils.updateNickName(userInfo.getNickname(),userInfo.getAccCode()));
			        EasemobIMUsers.createNewIMUserSingle(datanode);
			        
					infoMap.put("userToken", userToken);
					infoMap.put("userInfo", userMap);
					
					String serverB = AppSecretUtil.getAppSecret(userInfo.getId().toString(), appA);
					infoMap.put("serverB", serverB);
				}
				//消息推送
				JSONObject object = new JSONObject();
				object.put("title", "系统消息");
				object.put("content", "漫长的等待终于盼来了您，接下来的日子由陪你守护！陪你使用秘诀第一步：赶紧完善资料并上传真实头像，让我们玩转任务，认识更多的新朋友吧");
				object.put("type", 201);
				object.put("paramId", userInfo.getId());
				AppPush.sendPush(object,userInfo.getUserPhone().split(","));
				
				SmsSendUtil.sendSmsFit(null, userInfo.getId(), userInfo.getId(), 201, "漫长的等待终于盼来了您，接下来的日子由陪你守护！陪你使用秘诀第一步：赶紧完善资料并上传真实头像，让我们玩转任务，认识更多的新朋友吧");
				
				infoMap.put("resultCode", Constants.SUCCESS);
				infoMap.put("resultDesc", "注册成功");
			} else {
				infoMap.put("resultCode", Constants.FAIL);
				infoMap.put("resultDesc", "网络请求失败");
			}
		} catch (Exception e) {
			infoMap.put("resultCode", Constants.EXCEPTION);
			infoMap.put("resultDesc", "网络请求失败");
			logger.error(e.getMessage(),e);
			throw e;
		}
		return infoMap;
	}
	
	/**
	 * 第三方注册登录
	 * @author Han Guohong
	 * @param request
	 * @param sex
	 * @param birthday
	 * @param nowProvince
	 * @param nowCity
	 * @param age
	 * @param userName
	 * @param thirdType
	 * @param thirdName
	 * @param nickname
	 * @param imageHead
	 * @param appA
	 * @param devNo
	 * @param channel
	 * @param devtype
	 * @return
	 */
	@Transactional
	public HashMap<String, Object> registerThirdUserLogin(HttpServletRequest request,
			Integer sex,
			String birthday,
			Integer nowProvince,
			Integer nowCity,
			Integer age,
			String userName,
			Integer thirdType,////三方类型：1QQ,2微信；3新浪微博
			String thirdName,
			String nickname,
			MultipartFile imageHead,
			String appA,  //交换参数
			String devNo,
			String channel,
			Integer devtype
			) {
		HashMap<String, Object> infoMap = new HashMap<String, Object>();
		try {
			UserLogin userLogin = new UserLogin();
			
			UserInfo userInfo = new UserInfo();
			userInfo.setAge(age);
			userInfo.setSex(sex);
			userInfo.setBirthday(birthday);
			userInfo.setNowProvince(nowProvince);
			userInfo.setNowCity(nowCity);
			userInfo.setIsPhone(1);
			userInfo.setActiveTime(new Date());
			
			userLogin.setUserName(userName);
			userLogin.setThirdtype(thirdType);
			userLogin.setThirdName(thirdName);
			
			/*UserLogin userLogin1 = userLoginMapper.selectByUserName(userName);
			if (userLogin1 != null) {
				infoMap.put("isExist", Constants.FAIL);
				infoMap.put("resultCode", Constants.SUCCESS);
				infoMap.put("resultDesc", "该用户已存在");
				return infoMap;
			}*/
			
			List<UserLogin> list = userLoginMapper.selectByUserName(userName);
			if(list.size() > 0){
				infoMap.put("isExist", Constants.FAIL);
				infoMap.put("resultCode", Constants.SUCCESS);
				infoMap.put("resultDesc", "该用户已存在");
				return infoMap;
			}
			
			int insertNum = userLoginMapper.registerThirdUserLogin(userLogin);
			if (insertNum != 0) {
				
				userInfo.setId(UUID.randomUUID().toString().replace("-", ""));
				
				String filePath = "/upload/headImg/"+userName+".png";
				// 判断文件是否为空
				if (imageHead != null && !imageHead.isEmpty()) {
					String resultPath = FileUtils.uploadFile(imageHead, filePath);
					userInfo.setImageHead(resultPath);
					
					ImgVo imgVo = new ImgVo();
					imgVo.setImgUrl(resultPath);
					imgVo.setParamId(userInfo.getId());
					imgVo.setType(2);
					RedisUtil.lpush(RedisConstants.IMG_CHECK.getBytes(), SerializeUtil.serialize(imgVo));
					/*Integer result = ImageFilterUtil.checkImg(imageHead);
					if(result == null){
						String resultPath = FileUtils.uploadFile(imageHead, filePath);
						userInfo.setImageHead(resultPath);
						
						ImageFilterResult image = new ImageFilterResult();
						image.setImgurl(resultPath);
						image.setUrltype("squareImage");
						imageFilterResultMapper.insert(image);
					}else{
						if(result == 0 || result == 1){
							String resultPath = FileUtils.uploadFile(imageHead, filePath);
							userInfo.setImageHead(resultPath);
							
							if(result == 1){
								ImageFilterResult image = new ImageFilterResult();
								image.setImgurl(resultPath);
								image.setUrltype("squareImage");
								imageFilterResultMapper.insert(image);
							}
						}
					}*/
				}else{
					userInfo.setImageHead("");
				}
				
				userInfo.setUserLoginId(userLogin.getId());
				if(StringUtils.isNotBlank(nickname)){
					userInfo.setNickname(nickname);
				}else{
					userInfo.setNickname(CommonUtils.getRandom());
				}
				userInfo.setUserPhone(userName);
				
				userInfo.setRegTime(new Date());
				userInfo.setActiveTime(new Date());
				userInfo.setUpdateTime(new Date());
				userInfo.setIsRank(1);
				
				if(StringUtils.isNotBlank(devNo)){
					userInfo.setDevNo(devNo);
				}
				if(StringUtils.isNotBlank(channel)){
					userInfo.setChannel(channel);
				}
				if(devtype != null){
					userInfo.setDevtype(devtype);
				}
				
				//int insertUserInfoNum = userInfoService.insertByUserLoginId(userInfo);
				int insertUserInfoNum = userInfoMapper.insertSelective(userInfo);
				
				if (insertUserInfoNum != 0) {
					infoMap.put("isExist", Constants.SUCCESS);
					infoMap.put("resultCode", Constants.SUCCESS);
					infoMap.put("resultDesc", "注册成功");
					//userInfo = selectByUserLoginId(userLogin.getId());
					userInfo = userInfoMapper.selectByPrimaryKey(userInfo.getId());
					
					int selfNum = getselfNum(userInfo);//获取资料得分
					userInfo.setSelfNum(selfNum);
					
					userInfo.setReputation(PeiniUtils.getCredit(userInfo,1));
					
					userInfoMapper.updateByPrimaryKey(userInfo);
					
					// 建立用户账户表
					UserAccount userAccount = new UserAccount();
					userAccount.setUserId(userInfo.getId());
					userAccountMapper.insertSelective(userAccount);
					
					LinkedHashMap<String, Object> userMap = new LinkedHashMap<String, Object>();
					
					// 登录成功生成新的token
					String userToken = UUID.randomUUID().toString().replace("-", "");
					
					userMap.put("id", userToken);
					//userMap.put("id", userInfo.getId());
					userMap.put("userLoginId", userInfo.getUserLoginId());
					userMap.put("nickname",
							StringUtils.isNotBlank(userInfo.getNickname()) ?PeiniUtils.updateNickName( userInfo.getNickname(), userInfo.getAccCode()): "");
					userMap.put("imageHead",
							StringUtils.isNotBlank(userInfo.getImageHead()) ? userInfo.getImageHead() : "");
					userMap.put("sex", userInfo.getSex());
					userMap.put("userPhone", userName);
					
					//EhcacheUtil.getInstance().put("userCache", userInfo.getId().toString(), userToken);
					UserRedisUtil.updateUserToken(userInfo.getId(), userToken);
					
					getNewAward(userInfo);
					
					// userInfoService.updateCredit(userInfo.getId());
					//PeiniUtils.regUserInfos.add(userInfo);
					RedisUtil.lpush(RedisConstants.USER_REG.getBytes(), SerializeUtil.serialize(userInfo));
					
					//将新用户信息写入缓存
					UserVo userVo = new UserVo();
					userVo.setAcountId(String.valueOf(userAccount.getId()));
					userVo.setUserId(userInfo.getId());
					UserRedisUtil.addUserToRedis(userVo);
					
					ObjectNode datanode = JsonNodeFactory.instance.objectNode();
			        datanode.put("username",userLogin.getUserName());
			        datanode.put("password", "123456");
			        datanode.put("nickname", PeiniUtils.updateNickName(userInfo.getNickname(),userInfo.getAccCode()));
			        EasemobIMUsers.createNewIMUserSingle(datanode);
			        
					//EhcacheUtil.getInstance().put("accCodeCache", "codeList", PeiniUtils.regUserInfos);
					infoMap.put("userToken", userToken);
					infoMap.put("userInfo", userMap);
					
					/*if(request.getSession().getAttribute("devNo") != null){
						AppActivityUser user = new AppActivityUser();
						user.setCreatetime(new Date());
						user.setId(UUID.randomUUID().toString().replace("-", ""));
						user.setUserid(userInfo.getId());
						if(StringUtils.isNotBlank(request.getSession().getAttribute("channel").toString())){
							user.setChannel(request.getSession().getAttribute("channel").toString());
						}
						if(StringUtils.isNotBlank(request.getSession().getAttribute("devNo").toString())){
							user.setDevNo(request.getSession().getAttribute("devNo").toString());
						}
						if(StringUtils.isNotBlank(request.getSession().getAttribute("devtype").toString())){
							user.setDevtype(Integer.parseInt(request.getSession().getAttribute("devtype").toString()));
						}
						appActivityUserMapper.insert(user);
					}*/
					
					String serverB = AppSecretUtil.getAppSecret(userInfo.getId().toString(), appA);
					infoMap.put("serverB", serverB);
				}
				//消息推送
				JSONObject object = new JSONObject();
				object.put("title", "系统消息");
				object.put("content", "漫长的等待终于盼来了您，接下来的日子由陪你守护！陪你使用秘诀第一步：赶紧完善资料并上传真实头像，让我们玩转任务，认识更多的新朋友吧");
				object.put("type", 201);
				object.put("paramId", userInfo.getId());
				AppPush.sendPush(object,userInfo.getUserPhone().split(","));
				//给发起人推送消息
				/*UserSms newuserSms = new UserSms();
				newuserSms.setSmsid(UUID.randomUUID().toString().replace("-", ""));
				newuserSms.setIsremind(0);
				newuserSms.setReceivdel(0);
				newuserSms.setSenddel(0);
				newuserSms.setParamid(userInfo.getId());
				newuserSms.setSendtime(new Date());
				newuserSms.setSmscontent("漫长的等待终于盼来了您，接下来的日子有陪你守护！陪你使用秘诀第一步：赶紧完善资料并上传真实头像，让我们玩转任务，认识更多的新朋友吧");
				newuserSms.setSmstype(201);
				newuserSms.setToid(userInfo.getId());
				userSmsMapper.insertSelective(newuserSms);*/
				SmsSendUtil.sendSmsFit(null, userInfo.getId(), userInfo.getId(), 201, "漫长的等待终于盼来了您，接下来的日子由陪你守护！陪你使用秘诀第一步：赶紧完善资料并上传真实头像，让我们玩转任务，认识更多的新朋友吧");
				
				infoMap.put("resultCode", Constants.SUCCESS);
				infoMap.put("resultDesc", "注册成功");
			} else {
				infoMap.put("resultCode", Constants.FAIL);
				infoMap.put("resultDesc", "网络请求失败");
			}
		} catch (Exception e) {
			infoMap.put("resultCode", Constants.EXCEPTION);
			infoMap.put("resultDesc", "网络请求失败");
			logger.error(e.getMessage(),e);
			throw e;
		}
		return infoMap;
	}
	
	/**
	 * 通过邀请注册
	 * @author Han Guohong
	 * @param request
	 * @param userName
	 * @param checkCode
	 * @param smsCode
	 * @param pass
	 * @param recId
	 * @param channel
	 * @param devtype
	 * @return
	 */
	public HashMap<String, Object> register_invite(HttpServletRequest request,
			String userName,
			String checkCode,
			String smsCode,
			String pass,
			String recId,
			String channel,
			Integer devtype
			) {
		
		HashMap<String, Object> infoMap = new HashMap<String, Object>();
		
		try {
			
			UserLogin userLogin = new UserLogin();
			
			UserInfo userInfo = new UserInfo();
			userInfo.setIsPhone(1);
			
			/*userLogin = userLoginMapper.selectByUserName(userName);
			if (userLogin != null) {
				infoMap.put("resultCode", Constants.FAIL);
				infoMap.put("resultDesc", "该用户已存在");
				return infoMap;
			}*/
			List<UserLogin> list = userLoginMapper.selectByUserName(userName);
			if(list.size() > 0){
				infoMap.put("resultCode", Constants.FAIL);
				infoMap.put("resultDesc", "该用户已存在");
				return infoMap;
			}
			
			userLogin = new UserLogin();
			userLogin.setUserPassword(MDUtil.encodePwd(pass));
			userLogin.setUserName(userName);
			// 插入用户登录表
			int insertNum = userLoginMapper.insertByUserLogin(userLogin);
			
			if (insertNum != 0) {
				
				//userLogin = userLoginService.selectByUserName(userName);
				userInfo.setUserLoginId(userLogin.getId());
				userInfo.setId(UUID.randomUUID().toString().replace("-", ""));
				userInfo.setNickname(CommonUtils.getRandom());
				userInfo.setUserPhone(userName);
				userInfo.setRegTime(new Date());
				userInfo.setIsPhone(1);
				userInfo.setRegTime(new Date());
				userInfo.setActiveTime(new Date());
				userInfo.setUpdateTime(new Date());
				userInfo.setIsRank(1);
				userInfo.setChannel("recommend");
				
				userInfo.setRecommendUserId(recId);
				if(StringUtils.isNotBlank(channel)){
					userInfo.setChannel(channel);
				}
				if(devtype != null){
					userInfo.setDevtype(devtype);
				}
				//int insertUserInfoNum = userInfoMapper.insertByUserLoginId(userInfo);
				int insertUserInfoNum = userInfoMapper.insertSelective(userInfo);
				if (insertUserInfoNum != 0) {
					//userInfo = userInfoService.selectByUserLoginId(userLogin.getId());
					userInfo = selectByPrimaryKey(userInfo.getId());
					
					// 建立用户账户表
					UserAccount userAccount = new UserAccount();
					userAccount.setUserId(userInfo.getId());
					userAccountMapper.insertSelective(userAccount);
					//userAccountService.insert(userInfo.getId());
					LinkedHashMap<String, Object> userMap = new LinkedHashMap<String, Object>();
					
					String userToken = UUID.randomUUID().toString().replace("-", "");
					
					// 登录成功生成新的token
					UserRedisUtil.updateUserToken(userInfo.getId(), userToken);
					
					// edit by han 2017-1-6
					// userInfoService.updateCredit(userInfo.getId());
					PeiniUtils.regUserInfos.add(userInfo);
					//EhcacheUtil.getInstance().put("accCodeCache", "codeList", PeiniUtils.regUserInfos);
					
					//将新用户信息写入缓存
					UserVo userVo = new UserVo();
					userVo.setAcountId(String.valueOf(userAccount.getId()));
					userVo.setUserId(userInfo.getId());
					userVo.setUserLoginId(userLogin.getId().toString());
					userVo.setBuyList(new BigDecimal("0"));
					userVo.setGoldList(new BigDecimal("0"));
					userVo.setIntegrityList(new BigDecimal("0"));
					UserRedisUtil.addUserToRedis(userVo);

					PeiniUtils.regUserInfos.add(userInfo);

					infoMap.put("resultCode", Constants.SUCCESS);
					infoMap.put("resultDesc", "注册成功");
				} else {
					infoMap.put("resultCode", Constants.FAIL);
					infoMap.put("resultDesc", "网络请求失败");
				}
			}
		} catch (Exception e) {
			infoMap.put("resultCode", Constants.EXCEPTION);
			infoMap.put("resultDesc", "网络请求失败");
			logger.error(e.getMessage(),e);
		}
		return infoMap;
	}
	
	/**
	 * 分配用户帐号
	 * @author Han Guohong
	 * @param userInfo
	 */
	@Transactional
	public void allotAccCode(UserInfo userInfo){
		AccountCode code = accountCodeMapper.getOnePlainCode();
		if(code != null){
			userInfo.setAccCode(code.getAccCode());
		}
		
		code.setIsReceive(1);
		code.setReceiveUserId(userInfo.getId());
		
		userInfo.setNickname(code.getAccCode());
		
		//userInfoService.regSuccess(userInfo, code);
		userInfoMapper.updateSelectiveByPrimaryKey(userInfo);
		accountCodeMapper.updateByPrimaryKeySelective(code);
	}
	
	/**
	 * 根据userId获取账号及身份相关信息
	 * @author Han Guohong
	 * @param userId
	 * @return
	 */
	public HashMap<String, Object> getUserInfoAndLoginAccountInfo(String userId){
		HashMap<String, Object> paramMap = new HashMap<String, Object>();
		paramMap.put("userId", userId);
		List<LinkedHashMap<String, Object>> userList = userInfoMapper.getUserInfoAndLoginAccountInfo(paramMap);
		if(userList.size() > 0){
			return userList.get(0);
		}else{
			return null;
		}
	}
	
	@Transactional
	public void regSuccess(UserInfo userInfo,AccountCode accountCode){
		userInfoMapper.updateSelectiveByPrimaryKey(userInfo);
		accountCodeMapper.updateByPrimaryKeySelective(accountCode);
	}
	
	public UserInfo selectByUserLoginId(int userLoginId) {
		UserInfo userInfoBean = userInfoMapper.selectByUserLoginId(userLoginId);
		return userInfoBean;
	}
	
	public int insertByUserLoginId(UserInfo userInfo){
		int insertNum=userInfoMapper.insertByUserLoginId(userInfo);
		return insertNum;
	}
	
	public UserInfo selectByUserId(String userId) {
		UserInfo userInfoBean = userInfoMapper.selectByUserId(userId);
		return userInfoBean;
	}
	
	public HashMap<String,Object> selectMapByUserId(String userId) {
		 HashMap<String,Object> userInfoMap = userInfoMapper.selectMapByUserId(userId);
		return userInfoMap;
	}
	
	public int updateByUserId(UserInfo userInfo){
		int updateNum=userInfoMapper.updateByUserId(userInfo);
		return updateNum;
	}
	
	public int updateByUserJudge(UserJudge userJudge){
		int result = userInfoMapper.updateByUserJudge(userJudge);
		return result;
	}
	
	public int updateImageByUserId(UserInfo userInfo){
		int updateNum=userInfoMapper.updateImageByUserId(userInfo);
		return updateNum;
	}
	
	public int updateUserInfoIsIdcardByUserId(String userId){
		int updateNum=userInfoMapper.updateUserInfoIsIdcardByUserId(userId);
		return updateNum;
	}
	
	@Transactional
	public int updateSwitchRank(UserInfo userInfo){
		try {
			int updateNum=userInfoMapper.updateSwitchRank(userInfo);			
			
			UserInfoExample userExample = new UserInfoExample();
			userExample.createCriteria().andGoldListGreaterThan(0);
			List<UserInfo> useList = userInfoMapper.selectByExample(userExample);
			
			List<LinkedHashMap<String,Object>> rankList = userInfoService.getRank(1, 1);
			
			for (UserInfo uInfo : useList) {
				uInfo.setGoldList(0);
				userInfoMapper.updateByPrimaryKey(uInfo);
				
				//更新缓存
				UserVo userVo = UserRedisUtil.getUserVoByUserId(uInfo.getId());
				userVo.setGoldList(new BigDecimal(0));
				UserRedisUtil.addUserToRedis(userVo);
			}
			for (int i = 0; i < rankList.size(); i++) {
				LinkedHashMap<String,Object> rank = rankList.get(i);
				UserInfo uInfo = new UserInfo();
				uInfo.setId(rank.get("userId").toString());
				uInfo.setGoldList(i+1);
				userInfoMapper.updateByPrimaryKeySelective(uInfo);
				
				//更新缓存
				UserVo userVo = UserRedisUtil.getUserVoByUserId(rank.get("userId").toString());
				userVo.setGoldList(new BigDecimal(i+1));
				UserRedisUtil.addUserToRedis(userVo);
			}
			
			userExample = new UserInfoExample();
			userExample.createCriteria().andBuyListGreaterThan(0);
			useList = userInfoMapper.selectByExample(userExample);
			
			rankList = userInfoService.getRank(1, 2);
			
			for (UserInfo uInfo : useList) {
				uInfo.setBuyList(0);
				userInfoMapper.updateByPrimaryKey(uInfo);
				
				//更新缓存
				UserVo userVo = UserRedisUtil.getUserVoByUserId(uInfo.getId());
				userVo.setBuyList(new BigDecimal(0));
				UserRedisUtil.addUserToRedis(userVo);
			}
			for (int i = 0; i < rankList.size(); i++) {
				LinkedHashMap<String,Object> rank = rankList.get(i);
				UserInfo uInfo = new UserInfo();
				uInfo.setId(rank.get("userId").toString());
				uInfo.setBuyList(i+1);
				userInfoMapper.updateByPrimaryKeySelective(uInfo);
				
				//更新缓存
				UserVo userVo = UserRedisUtil.getUserVoByUserId(rank.get("userId").toString());
				userVo.setBuyList(new BigDecimal(i+1));
				UserRedisUtil.addUserToRedis(userVo);
			}
			
			//PeiniUtils.getCredit(userInfo, 1);
			userExample = new UserInfoExample();
			userExample.createCriteria().andBuyListGreaterThan(0);
			useList = userInfoMapper.selectByExample(userExample);
			
			rankList = userInfoService.getRank(1, 3);
			
			for (UserInfo uInfo : useList) {
				UserInfo u = new UserInfo();
				u.setId(userInfo.getId());					
				u.setIntegrityList(0);
				//userInfoMapper.updateByPrimaryKey(userInfo);
				userInfoMapper.updateByPrimaryKeySelective(u);
				
				//更新缓存
				UserVo userVo = UserRedisUtil.getUserVoByUserId(uInfo.getId());
				userVo.setIntegrityList(new BigDecimal("0"));
				UserRedisUtil.addUserToRedis(userVo);
			}
			for (int i = 0; i < rankList.size(); i++) {
				LinkedHashMap<String,Object> rank = rankList.get(i);
				UserInfo uInfo = new UserInfo();
				uInfo.setId(rank.get("userId").toString());
				uInfo.setIntegrityList(i+1);
				userInfoMapper.updateByPrimaryKeySelective(uInfo);
				
				//更新缓存
				UserVo userVo = UserRedisUtil.getUserVoByUserId(rank.get("userId").toString());
				if(userVo != null){
					userVo.setIntegrityList(new BigDecimal(i+1));
					UserRedisUtil.addUserToRedis(userVo);
				}
			}
			
			return updateNum;
		} catch (Exception e) {
			logger.error(e.getMessage(),e);
			throw e;
		}
	}
	
	public int getSwitchRank(String id){
		int userInfo=userInfoMapper.getSwitchRank(id);
		return userInfo;
	}
	
	/*public int updateUserInfoTaskNumByPlusAndMinus(String userId,int Num){
		UserInfo userInfo=new UserInfo();
		userInfo.setId(userId);
		int taskNum=userInfoMapper.selectTaskNumByUserId(userInfo.getId());
		if (taskNum+Num>=1000) {
			userInfo.setTaskNum(1000);
		}else{
			userInfo.setTaskNum(taskNum+Num);
		}
		
		int returnNum=userInfoMapper.updateUserInfoTaskNumByPlusAndMinus(userInfo);
		return returnNum;
	}*/
	
	/**
	 * 获取任务分
	 * @author Han Guohong
	 * @param userId
	 * @param Num
	 * @return
	 */
	public int getTaskNum(String userId,int Num){
		UserInfo userInfo=new UserInfo();
		userInfo.setId(userId);
		int taskNum=userInfoMapper.selectTaskNumByUserId(userInfo.getId());
		if (taskNum+Num>=1000) {
			return 1000;
		}else{
			return taskNum+Num;
		}
	}
	
	//获取资料得分
	public int getselfNum(UserInfo userInfo){
		int num = 0;
		if(StringUtils.isNotBlank(userInfo.getNickname())){//昵称
			num += 5;
		}
		if(userInfo.getSex()!=null && !userInfo.getSex().equals(0)){//性别
			num += 5;
		}
		if(userInfo.getAge()!=null && !userInfo.getAge().equals(0)){//年龄
			num += 5;
		}
		if(userInfo.getHeight()!=null && !userInfo.getHeight().equals(0)){//身高
			num += 5;
		}
		if(userInfo.getWeight()!=null && !userInfo.getWeight().equals(0)){//体重
			num += 5;
		}
		if(userInfo.getOldProvince()!=null && !userInfo.getOldProvince().equals(0)){//故乡
			num += 5;
		}
		if(userInfo.getNowProvince()!=null && !userInfo.getNowProvince().equals(0)){//所在地
			num += 5;
		}
		if(userInfo.getConstellation()!=null && !userInfo.getConstellation().equals(0)){//星座
			num += 5;
		}
		if(userInfo.getNation()!=null && !userInfo.getNation().equals(0)){//民族
			num += 5;
		}
		if(userInfo.getEmotion()!=null && !userInfo.getEmotion().equals(0)){//感情
			num += 5;
		}
		if(userInfo.getDegree()!=null && !userInfo.getDegree().equals(0)){//学历
			num += 10;
		}
		if(userInfo.getSmallIncome()!=null && !userInfo.getSmallIncome().equals(0)){//收入
			num += 10;
		}
		if(userInfo.getIndustry()!=null && !userInfo.getIndustry().equals(0)){//行业
			num += 10;
		}
		if(userInfo.getIsCar()!=null && !userInfo.getIsCar().equals(0)){//车
			num += 10;
		}
		if(userInfo.getIsHouse()!=null && !userInfo.getIsHouse().equals(0)){//房
			num += 10;
		}
		return num;
	}
	
	//获取信用值
	public int getCredit(UserInfo userInfo){
		int num = 0;
		if(userInfo.getTaskNum()>0){
			num = userInfo.getSelfNum()*3/10 + userInfo.getIdcardNum()*2/10 + userInfo.getTaskNum()*5/100;
		}else{//任务如果是负数则不计算
			num = userInfo.getSelfNum()*3/10 + userInfo.getIdcardNum()*2/10;
		}
		return num;
	}
	
	//信用度变更
	public int updateCredit(String userId){
		UserInfo userInfo=userInfoMapper.selectByUserId(userId);
		userInfo.setReputation(this.getCredit(userInfo));
		int num=userInfoMapper.updateCreditByUserId(userInfo);
		return num;
	}
	
	public List<LinkedHashMap<String,Object>> getRank(int dType,int rType){
		List<LinkedHashMap<String,Object>> userMap = new ArrayList<LinkedHashMap<String,Object>>();
		if(rType==1){//金币
			userMap = userInfoMapper.getGoldRank(dType);
		}else if(rType==2){//土豪
			userMap = userInfoMapper.getMoneyRank(dType);
		}else{//信用
			userMap = userInfoMapper.getReputationRank(dType);
		}
		return userMap;
	}
	
	public HashMap<String, Object> getUserRank(int dType,int rType,String userId){
		HashMap<String,Object> userMap = new HashMap<String,Object>(); 
		HashMap<String,Object> rankMap = new HashMap<String,Object>(); 
		rankMap.put("dType", dType);
		rankMap.put("userId", userId);
		if(rType==1){//金币
			userMap = userInfoMapper.getUserGoldRank(rankMap);
		}else if(rType==2){//土豪
			userMap = userInfoMapper.getUserMoneyRank(rankMap);
		}else{//信用
			userMap = userInfoMapper.getUserReputationRank(rankMap);
		}
		return userMap;
	}
	
	public List<UserInfo> searchUserInfo( UserSearchVo vo){
		PageHelper.startPage(vo.getPageNum(), vo.getPageSize());
		UserInfoExample example = new UserInfoExample();
		example.xpoint = vo.getXpoint();
		example.ypoint = vo.getYpoint();
		Criteria criterial = example.createCriteria();
		
		//性别
		if(vo.getSex() == 0 || vo.getSex() == 1){
			criterial.andSexEqualTo(vo.getSex());
		}
		
		//活跃时间
		int timeLimit = 0;
		switch(vo.getActiveTime()){
			case 1:
				timeLimit = 900;  //15分钟
				break;
			case 2:
				timeLimit = 3600;  //1小时
				break;
			case 3:
				timeLimit = 3600 * 24;    //1天
				break;
			default:
				timeLimit = 3600 * 72;    //3天
				break;
		}
		Calendar c = Calendar.getInstance();
		c.add(Calendar.SECOND, 0 - timeLimit);
		criterial.andActiveTimeGreaterThanOrEqualTo(c.getTime());
		
		//年龄
		if(vo.getLowAge() > 0){
			criterial.andAgeGreaterThanOrEqualTo(vo.getLowAge());
		}
		if(vo.getHighAge() > 0){
			criterial.andAgeLessThanOrEqualTo(vo.getHighAge());
		}
		
		if(vo.isHouse()){
			criterial.andIsHouseEqualTo(1);
		}
		if(vo.isCar()){
			criterial.andIsCarEqualTo(1);
		}
		if(vo.getIndustry() > 0){
			criterial.andIndustryEqualTo(vo.getIndustry());
		}
		if(vo.getLowHeight() > 0){
			criterial.andHeightGreaterThanOrEqualTo(vo.getLowHeight());
		}
		if(vo.getHighHeight() > 0){
			criterial.andHeightLessThanOrEqualTo(vo.getHighHeight());
		}
		if(vo.getLowWeight() > 0){
			criterial.andWeightGreaterThanOrEqualTo(vo.getLowWeight());
		}
		if(vo.getHighWeight() > 0){
			criterial.andWeightLessThanOrEqualTo(vo.getHighWeight());
		}
		if(vo.getOldCity() > 0){
			criterial.andOldCityEqualTo(vo.getOldCity());
		}
		if(vo.getConstellation() > 0){
			criterial.andConstellationEqualTo(vo.getConstellation());
		}
		if(vo.getNation() > 0){
			criterial.andNationEqualTo(vo.getNation());
		}
		if(vo.getEmotion() > 0){
			criterial.andEmotionEqualTo(vo.getEmotion());
		}
		if(vo.getDegree() > 0){
			criterial.andDegreeEqualTo(vo.getDegree());
		}
		if(vo.getSmallIncome() > 0){
			criterial.andBigIncomeGreaterThan(vo.getSmallIncome());
		}
		if(vo.getBigIncome() > 0){
			criterial.andSmallIncomeLessThan(vo.getBigIncome());
		}
		return userInfoMapper.selectByExampleWithDistance(example);
	}
	
	public UserInfo selectByPrimaryKey(String id){
		return userInfoMapper.selectByPrimaryKey(id);
	}

	public void updateByPrimaryKeySelective(UserInfo info) {
		userInfoMapper.updateByPrimaryKeySelective(info);
	}
}
